package com.hjj.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
@Component
public class LoginFilter extends ZuulFilter {
	/**
	 * 选择过滤器类型, 有预定义常量值
	 * @return
	 */
	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}

	/**
	 * 设置过滤器的优先级顺序,多个同级时,可以+/-1来设置循序
	 * @return
	 */
	@Override
	public int filterOrder() {
		return FilterConstants.PRE_DECORATION_FILTER_ORDER-1;
	}

	/**
	 * 获取request里的url,从上下文RequestContext中获取
	 * return true 时拦截
	 * @return
	 */
	@Override
	public boolean shouldFilter() {
		RequestContext currentContext = RequestContext.getCurrentContext();
		HttpServletRequest request = currentContext.getRequest();
		String uri = request.getRequestURI();
		return "/web/web/items".equals(uri);
	}

	/**
	 * 举例处理过滤的执行逻辑
	 * @return
	 * @throws ZuulException
	 */
	@Override
	public Object run() throws ZuulException {
		RequestContext currentContext = RequestContext.getCurrentContext();
		HttpServletRequest request = currentContext.getRequest();
		if (request.getParameter("id")==null || "".equals(request.getParameter("id"))){
			currentContext.setResponseStatusCode(403);
			currentContext.setResponseBody("please input id");
			currentContext.setSendZuulResponse(false);
		}

		return null;
	}
}
